/**
 * 统计图表
 * date:17/12/28 11:47
 */

/**
 * 通话统计/饼图(多图)
 */
var TalkMultiChart = {
    new:function(){
        var chart = {};
        chart.title = [];           // 图标标题
        chart.chartId = "";         // 图表的页面dom标识
        chart.chartObj = null;      // echarts对象
        chart.countDatas = [];      // 通话次数统计数据
        chart.theme = "default";    // 主题
        //初始化echart对象
        chart.init = function(){
            chart.chartObj = echarts.init($(chart.chartId, navTab.getCurrentPanel())[0], chart.theme);
        };
        //加载图形
        chart.load = function() {
            chart.init();
            chart.setOption();
        };
        chart.setOption = function() {
            var option = {
                title: chart.title,
                tooltip: {
                    trigger: 'item',
                    formatter: "{a} <br/>{b}占比: {d}%"
                },
                series: chart.countDatas
            }
            chart.chartObj.setOption(option);
        };
        return chart;
    },
    formatLabel: function(params) {
        return params.name + "\r\n" + params.value;
    },
    formatDurationLabel: function(params) {
        return params.name + "\r\n" + date.descDuration(params.value);
    }
}


/**
 * 放款金额、笔数增长曲线/柱图
 */
var LineBarCharts = {
    new:function(){
        var chart = {};
        chart.title = "";             // 图表标题
        chart.chartId = "";           // 图表的页面dom标识
        chart.chartObj = null;        // echarts对象
        chart.url = "";               // 服务url
        chart.urlParams = {};         // 查询参数
        chart.dates = [];             // x坐标,时间刻度列表
        chart.shops = [];             // 网点名称列表
        chart.amountDatas = [];       // 放款金额数据
        chart.numberDatas = [];       // 放款笔数数据
        chart.colors =  ['#3A99D8', '#d66335']; // 曲线/柱图颜色
        chart.theme = "shine";                  // 主题
        //初始化echart对象
        chart.init = function(){
            chart.dates = [];
            chart.amountDatas = [];
            chart.numberDatas = [];
            chart.chartObj = echarts.init($(chart.chartId, navTab.getCurrentPanel())[0], chart.theme);
        };
        //加载图形
        chart.load = function() {
            chart.init();
            $.ajax({type:"Post", url:chart.url,
                data:chart.urlParams,
                dataType:"json",
                success:function(json) {
                    for(var i=0; i<json.length; i++) {
                        chart.dates.push(json[i].date);
                    }
                    for(var i=0; i<json.length; i++) {
                        chart.amountDatas.push(json[i].loanCount.amount);
                    }
                    for(var i=0; i<json.length; i++) {
                        chart.numberDatas.push(json[i].loanCount.number);
                    }
                    chart.setOption();
                },
                error:function(XMLHttpRequest, textStatus, errorThrown){ }
            });
        };
        chart.setOption = function() {
            var option = {
                color:chart.colors,
                title:{ text:chart.title, left:'center', textStyle:{ color:'#4b4b4b', fontWeight:'normal'} },
                tooltip:{
                    trigger:'axis',
                    position:function (pos, params, dom, rect, size) {
                        if(pos[0] > size.viewSize[0] / 2) {
                            return { left:(pos[0] - dom.offsetWidth - 30), top:50 }
                        } else {
                            return { left:(pos[0] + 30), top:50 }
                        }
                    }
                },
                toolbox:{
                    feature:{
                        magicType:{ type:['line', 'bar'] },
                        restore :{ show:true }
                    }
                },
                legend:{
                    data:['笔数','金额'],
                    left:'20',
                },
                grid:{ left:'20px', right:'40px', top:'60px', bottom:'40px', containLabel:true },
                xAxis:{
                    type:'category',
                    axisTick:{
                        alignWithLabel:true
                    },
                    data:chart.dates
                },
                yAxis:{
                    type:'value',
                    axisLabel:{
                        formatter:function(params) {
                            return numberUtil.splitFormatted(params.value) + " 万";
                        }
                    }
                },
                yAxis:[
                    {
                        type:'value',
                        name:'金额',
                        position:'left',
                        axisLine:{
                            lineStyle:{
                                color:chart.colors[0]
                            }
                        },
                        axisLabel:{
                            formatter:function(value) {
                                return numberUtil.splitFormatted(value/10000) + " 万";
                            }
                        }
                    },
                    {
                        type:'value',
                        name:'笔数',
                        position:'right',
                        axisLine:{
                            lineStyle:{
                                color:chart.colors[1]
                            }
                        },
                        axisLabel:{
                            formatter:'{value} 笔'
                        }
                    }
                ],
                series:[
                    {
                        name:'金额',
                        type:'bar',
                        yAxisIndex:0,
                        barWidth:'25%',
                        label:{
                            normal:{
                                show:true,
                                position:'top',
                                formatter:function(params) {
                                    return numberUtil.splitFormatted(params.value/10000) + "万";
                                }
                            }
                        },
                        data:chart.amountDatas
                    },
                    {
                        name:'笔数',
                        type:'line',
                        yAxisIndex:1,
                        barWidth:'25%',
                        label:{
                            normal:{
                                show:true,
                                position:[15, 5],
                                textStyle:{ color:'#D28268'}
                            }
                        },
                        data:chart.numberDatas
                    }
                ]
            }
            chart.chartObj.setOption(option);
        };
        return chart;
    }
}

/**
 * 放款金额增长曲线图
 */
var LineCharts = {
    new:function(){
        var chart = {};
        chart.title = "";          // 图表标题
        chart.chartId = "";        // 图表的页面dom标识
        chart.chartObj = null;     // echarts对象
        chart.url = "";            // 服务url
        chart.urlParams = {};      // 查询参数
        chart.datas = [];          // x坐标,时间刻度列表
        chart.shops = [];          // 网点名称列表
        chart.amountDatas = [];    // 放款金额数据
        chart.theme = "shine";     // 主题
        //初始化echart对象
        chart.init = function(){
            chart.dates = [];
            chart.amountDatas = [];
            chart.chartObj = echarts.init($(chart.chartId, navTab.getCurrentPanel())[0], chart.theme);
        };
        //加载图形
        chart.load = function() {
            chart.init();
            $.ajax({type:"Post", url:chart.url,
                data:chart.urlParams,
                dataType:"json",
                success:function(json) {
                    for(var i=0; i<json.length; i++) {
                        chart.dates.push(json[i].date);
                    }
                    for(var i=0; i<chart.shops.length; i++) {
                        var amounts = [];
                        for(var j=0; j<json.length; j++) {
                            amounts.push(json[j].loanCounts[i+1].amount);
                        }
                        chart.amountDatas.push({ name:chart.shops[i], type:'line', data:amounts });
                    }
                    chart.setOption();
                },
                error:function(XMLHttpRequest, textStatus, errorThrown){ }
            });
        };
        chart.setOption = function() {
            var option = {
                title:{ text:'' },
                tooltip:{
                    trigger:'axis',
                    position:function (pos, params, dom, rect, size) {
                        if(pos[0] > size.viewSize[0] / 2) {
                            return { left:(pos[0] - dom.offsetWidth - 30), top:50 }
                        } else {
                            return { left:(pos[0] + 30), top:50 }
                        }
                    }
                },
                toolbox:{
                    feature:{ magicType:{ type:['line', 'bar'] } }
                },
                legend:{
                    data:chart.shops
                },
                grid:{ left:'15px', right:'50px', top:'50px', bottom:'40px', containLabel:true },
                xAxis:{
                    type:'category',
                    boundaryGap:false,
                    data:chart.dates
                },
                yAxis:{ type:'value' },
                series:chart.amountDatas
            }
            chart.chartObj.setOption(option);
        };
        return chart;
    }
}


/**
 * 放款金额占比饼图
 */
var PieCharts = {
    new:function(){
        var chart = {};
        chart.title = "";           // 图表标题
        chart.titleTmp = "";
        chart.chartId = "";         // 图表的页面dom标识
        chart.chartObj = null;      // echarts对象
        chart.url = "";             // 服务url
        chart.urlParams = {};       // 查询参数
        chart.shops = [];           // 网点名称列表
        chart.amountDatas = [];     // 放款金额数据
        chart.theme = "shine";      // 主题
        chart.showDate = false;     // 显示统计区间
        //初始化echart对象
        chart.init = function(){
            chart.amountDatas = [];
            chart.chartObj = echarts.init($(chart.chartId, navTab.getCurrentPanel())[0], chart.theme);
        };
        //加载图形
        chart.load = function() {
            chart.init();
            $.ajax({type:"Post", url:chart.url,
                data:chart.urlParams,
                dataType:"json",
                success:function(json) {
                    if(chart.showDate) {
                        chart.titleTmp = chart.title + " (" + json.date + ")";
                    } else {
                        chart.titleTmp = chart.title;
                    }
                    for(var i=0; i< chart.shops.length; i++) {
                        chart.amountDatas.push({ name:chart.shops[i], value:json.loanCounts[i+1].amount });
                    }
                    chart.setOption();
                },
                error:function(XMLHttpRequest, textStatus, errorThrown){ }
            });
        };
        chart.setOption = function() {
            var option = {
                title:{ text:chart.titleTmp, x:'center', textStyle:{ color:'#4b4b4b', fontWeight:'normal'}  },
                // tooltip:{ trigger:'item', formatter:function(params) {
                //     return params.name + "<br/>" + numberUtil.splitFormatted(params.value/10000) + "万 (" + params.percent + "%)";
                // } },
                toolbox:{
                    feature:{  }
                },
                legend:{
                    orient:'vertical',
                    x:'30',
                    data:chart.shops
                },
                grid:{ left:'15px', right:'50px', top:'50px', bottom:'40px', containLabel:true },
                series:[
                    {
                        type:'pie',
                        radius :'65%',
                        center:['50%', '50%'],
                        selectedMode:'single',
                        label:{ normal:{
                            formatter:function(params) {
                                return params.name + " " + numberUtil.splitFormatted(params.value/10000) + "万 (" + params.percent + "%)";
                            }
                        }},
                        data:chart.amountDatas
                    }
                ]
            }
            chart.chartObj.setOption(option);
        };
        return chart;
    }
}

/**
 * 密切度雷达图
 */
var RadarCharts = {
    new:function () {
        var chart = {};
        chart.title = "";               // 图表标题
        chart.titleTmp = "";
        chart.chartId = "";             // 图表的页面dom标识
        chart.chartObj = null;          // echarts对象
        chart.socialIndicators = [];  // 密切度指标
        chart.socialDatas = [];       // 密切度数据
        chart.theme = "shine";          // 主题
        //初始化echart对象
        chart.init = function () {
            chart.chartObj = echarts.init($(chart.chartId, navTab.getCurrentPanel())[0]);
        };
        //加载图形
        chart.load = function () {
            chart.init();
            var indicators = [];
            for (var i = 0; i < chart.socialIndicators.length; i++) {
                indicators.push({name:chart.socialIndicators[i], max:1});
            }
            chart.socialIndicators = indicators;
            chart.socialDatas[0] = numberUtil.scale(chart.socialDatas[0]);
            chart.socialDatas[1] = numberUtil.scale(chart.socialDatas[1]);
            chart.socialDatas[2] = numberUtil.scale(chart.socialDatas[2]);
            chart.setOption();
        };
        chart.setOption = function () {
            var option = {
                title:{text:chart.titleTmp, x:'center', textStyle:{color:'#4b4b4b', fontWeight:'normal'}},
                tooltip:{trigger:'axis'},
                toolbox:{
                    feature:{}
                },
                radar:{
                    indicator:chart.socialIndicators,
                    center:['50%', '55%'],
                    radius:160
                },
                series:[
                    {
                        type:'radar',
                        tooltip:{trigger:'item'},
                        data:[{
                            value:chart.socialDatas,
                            name:'密切度：',
                            areaStyle:{color:'#D23B3A', opacity:0.8}
                        }]
                    }
                ]
            }
            chart.chartObj.setOption(option);
        };
        return chart;
    }
}

/**
 * 客户关系图
 */
var GraphCharts = {
    new:function(){
        var chart = {};
        chart.title = "密切度关系图";     // 图表标题
        chart.chartId = "";             // 图表的页面dom标识
        chart.chartObj = null;          // echarts对象
        chart.url = "";                 // 服务url
        chart.urlParams = {};           // 查询参数
        chart.userLinks = [];           // 客户关系列表
        chart.userDatas = [];           // 客户信息列表
        chart.theme = "shine";          // 主题
        chart.isInit = false;           // 是否已初始化
        chart.shipType = { HOME:1, COMPANY:2, TALK:3 }; //密切度关系类型，0已预留给Master
        //初始化echart对象
        chart.init = function(){
            chart.userLinks = [];
            chart.userDatas = [];
            if(chart.isInit) { return; }
            chart.chartObj = echarts.init($(chart.chartId, navTab.getCurrentPanel())[0], chart.theme);
            chart.chartObj.on('click', function (params) {
                if(params.seriesType === "graph") {
                    if(params.data.category > 0) {
                        chart.urlParams = { userId:params.data.id };
                        chart.load();
                    }
                }
            });
            chart.isInit = true;
        };
        //加载图形
        chart.load = function() {
            chart.init();
            //chart.chartObj.showLoading();
            $.ajax({type:"Post", url:chart.url,
                data:chart.urlParams,
                dataType:"json",
                success:function(json) {
                    var userIndexMap = new HashMap();   //客户索引Map
                    var userIndex = 0;                  //客户索引
                    var shipList = new Array();         //客户关系列表
                    var shipMap = new HashMap();        //客户关系<->关系类型Map，key:userId-socialUserId，value:邻居/同事/熟人
                    var ship = "0-0"                    //客户关系
                    var shipType;                       //客户关系类型
                    var parentUserId = 0;
                    var item;

                    //Master(category为0)
                    parentUserId = json.socialUserId;
                    userIndexMap.put(json.socialUserId, userIndex);
                    chart.userDatas.push({ id:json.socialUserId, name:json.socialUsername, number:userIndex, showNum:0, category:0, value:70, draggable:true, x:null, y:null });

                    /**
                     * 取得客户信息列表，并为其创建索引，建立客户及关系Map表/List表
                     */
                    //关系人物及关系类型
                    for(var i=0; i<json.list.length; i++) {
                        item = json.list[i];
                        if(userIndexMap.containsKey(item.socialUserId)) { continue; }

                        userIndex++;
                        userIndexMap.put(item.socialUserId, userIndex);

                        ship = parentUserId + "-" + item.socialUserId;
                        shipType = chart.relationShipType(item);
                        shipMap.put(ship, shipType.label);
                        shipList.push(ship);
                        chart.userDatas.push({ id:item.socialUserId, name:item.socialUsername, number:userIndex, showNum:item.total, category:shipType.type, value:50, draggable:true, x:null, y:null });
                    }
                    for(var i=0; i<json.list.length; i++) {

                        parentUserId = json.list[i].socialUserId;
                        for(var j=0; j<json.list[i].list.length; j++) {
                            item = json.list[i].list[j];

                            if(!userIndexMap.containsKey(item.socialUserId)) {
                                userIndex++;
                                userIndexMap.put(item.socialUserId, userIndex);
                                chart.userDatas.push({ id:item.socialUserId, name:item.socialUsername, number:userIndex, showNum:item.total,  category:shipType.type, value:40, draggable:true, x:null, y:null });
                            }

                            //注意此处可能存在重复的客户关系，如A-B和B-A同时先后加入列表中
                            ship = parentUserId + "-" + item.socialUserId;
                            shipType = chart.relationShipType(item);
                            shipMap.put(ship, shipType.label);
                            shipList.push(ship);
                        }
                    }

                    /**
                     * 排除重复的客户关系，建立GraphChart所需客户关系数据
                     */
                    var finalShipList = new Array();
                    var userIds = [];
                    for(var i=0; i<shipList.length; i++) {
                        userIds = shipList[i].split('-');
                        if(finalShipList.indexOf(userIds[0] + "-" + userIds[1]) == -1 && finalShipList.indexOf(userIds[1] + "-" + userIds[0]) == -1) {
                            finalShipList.push(userIds[0] + "-" + userIds[1]);
                        }
                        for(var j=i+1; j<shipList.length; j++) {
                            userIds = shipList[j].split('-');
                            if(finalShipList.indexOf(userIds[0] + "-" + userIds[1]) == -1 && finalShipList.indexOf(userIds[1] + "-" + userIds[0]) == -1) {
                                finalShipList.push(userIds[0] + "-" + userIds[1]);
                            }
                        }
                    }
                    for(var i=0; i<finalShipList.length; i++) {
                        userIds = finalShipList[i].split('-');
                        ship = userIds[0] + "-" + userIds[1];
                        chart.userLinks.push({ source:userIds[0], target:userIds[1], value:shipMap.get(ship) })
                    }

                    //chart.chartObj.hideLoading();
                    chart.setOption();
                },
                error:function(XMLHttpRequest, textStatus, errorThrown){ }
            });
        };
        chart.relationShipType = function(item){
            var type = 0;
            var label = [];
            if(item.home > 0) {
                type = chart.shipType.HOME;
                label.push("邻居");
            }
            if(item.company > 0) {
                type = chart.shipType.COMPANY;
                label.push("同事");
            }
            if(item.talk > 0) {  //优先
                type = chart.shipType.TALK;
                label.push("熟人");
            }
            return { type:type, label:label.toString()}
        };
        chart.setOption = function() {
            var option = {
                animationDurationUpdate:1500,
                animationEasingUpdate:'quinticInOut',
                title:{ text:chart.titleTmp, x:'center', textStyle:{ color:'#4b4b4b', fontWeight:'normal'}  },
                tooltip:{},
                legend:{ show:'show', x:'center', data:[] },
                series:[
                    {
                        type:'graph',
                        roam:true,
                        layout:'force',
                        force:{ repulsion:1200, edgeLength:[50, 200] },
                        focusNodeAdjacency:true,
                        tooltip:{
                            formatter:function(node) {
                                if (node.data.category > 0) {
                                    return "密切度:" + numberUtil.scale(node.data.showNum * 100) + " %";
                                }
                            }
                        },
                        label:{
                            normal:{  show:true, textStyle:{ fontSize:12 } }
                        },
                        lineStyle:{  normal:{ opacity:0.85, width:1, curveness:0.0 }},
                        symbolSize:function(size) { return size; },
                        edgeSymbol:['circle', 'arrow'],
                        edgeSymbolSize:[1, 6],
                        edgeLabel:{
                            normal:{ show:true, textStyle:{ fontSize:10 }, formatter:"{@value}" }
                        },
                        categories:[
                            { name:'Master', itemStyle:{ normal:{ color:"#304553" }} },
                            { name:'邻居', itemStyle:{ normal:{ color:"#C03636" }} },
                            { name:'同事', itemStyle:{ normal:{ color:"#D28268" }} },
                            { name:'熟人', itemStyle:{ normal:{ color:"#63A0A7" }} }
                        ],
                        data:chart.userDatas,
                        links:chart.userLinks
                    }
                ]
            }
            chart.chartObj.setOption(option);
        };
        return chart;
    }
}